package com.mutual.help.service.Impl;

import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mutual.help.dao.WxUserMapper;
import com.mutual.help.entity.WxUsers;
import com.mutual.help.service.WxUserService;
import com.mutual.help.utils.WeChatResponseUtil;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class WxUserServiceImpl extends ServiceImpl<WxUserMapper, WxUsers> implements WxUserService {

    private final WxMaServiceImpl wxMaService = new WxMaServiceImpl();

    private final String Appid = "wxeccd0dd38dadef1f";

    private final String Secret = "10e8b0b0ce0950672996a9024d5ea997";

    @Override
    public Object userOpenId(String code, String userId) {
        Date date = new Date();
        WxUsers user = new WxUsers();
        user.setUserId(userId);
        if (code == null) {
            return WeChatResponseUtil.badArgument();
        }
        String sessionKey = null;
        String openId = null;
        WxMaInMemoryConfig wxMaInMemoryConfig = new WxMaInMemoryConfig();
        wxMaInMemoryConfig.setAppid(Appid);
        wxMaInMemoryConfig.setSecret(Secret);
        wxMaService.setWxMaConfig(wxMaInMemoryConfig);
        try {
            WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
            user.setOpenId(openId);
            if(baseMapper.updateById(user)>0)
                return WeChatResponseUtil.ok();
            else
                return WeChatResponseUtil.fail();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sessionKey == null || openId == null) {
            return WeChatResponseUtil.fail();
        }else {
            return WeChatResponseUtil.ok();
        }
    }

    @Override
    public Object addCustomUser(String nickName, String gender, String avatarUrl, String country) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = format.format(date);
        WxUsers wxUsers = new WxUsers();
        wxUsers.setUserId(dateString);
        wxUsers.setGender(gender);
        wxUsers.setNickName(nickName);
        wxUsers.setAvatarUrl(avatarUrl);
        wxUsers.setCountry(country);
        WxUsers dbUser = baseMapper.selectByNickName(nickName);
        if (dbUser == null){
            baseMapper.insert(wxUsers);//首次登录插入数据
            return WeChatResponseUtil.ok("200", dateString);
        }else {
            wxUsers.setUserId(dbUser.getUserId());
            baseMapper.updateById(wxUsers);
            return WeChatResponseUtil.ok("201", dbUser.getUserId());
        }
    }
}
